//59.螺旋矩阵II
//https://leetcode.cn/problems/spiral-matrix-ii/
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ret(n,vector<int>(n));

        //上下左右区间
        int u = 0,d = n-1,l = 0,r = n-1;
        int cnt = 1; //记录写入的数
        while(cnt <= n*n)
        {
            //顶行
            for(int i = l;i<=r && cnt<=n*n;++i) ret[u][i] = cnt++;
            ++u;

            //右列
            for(int i = u;i<=d && cnt<=n*n;++i) ret[i][r] = cnt++;
            --r;

            //底行
            for(int i = r;i>=l && cnt<=n*n;--i) ret[d][i] = cnt++;
            --d;

            //左列
            for(int i = d;i>=u && cnt<=n*n;--i) ret[i][l] = cnt++;
            ++l;
        }
        return ret;
    }
};